import { useState, useEffect, useRef } from "react";
import { Button, Input, Table, Modal, InputRef, message } from "antd";
import globalStore from "../../store/globalStore";
import api from "../../api";
const { reqCatrGread, reqChangeNewsCategory, reqDelNewsCategory } = api;
const { confirm } = Modal;
interface slectType {
  id: number;
  title: string;
  value: string;
}

type arrData = Array<slectType>;

export default function index() {
  const [data, useData] = useState<arrData>([]);
  const [inputStuts, useInputStuts] = useState<{ [name: string]: boolean }>({});
  const input = useRef<InputRef>(null);
  const getReviewData = async () => {
    const reuslt = (await reqCatrGread()) as unknown as arrData;
    useInputStuts(
      reuslt.reduce<{ [name: string]: boolean }>((value, item) => {
        value[item.value] = false;
        return value;
      }, {})
    );
    useData(reuslt);
  };
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "栏目名称",
      dataIndex: "value",
      key: "value",
      render(value: string, item: slectType) {
        if (inputStuts[value]) {
          return (
            <Input
              ref={input}
              defaultValue={value}
              style={{ width: "100px" }}
              onBlur={async ({ target }) => {
                if (target.value) {
                  await reqChangeNewsCategory(item.id, target.value);
                  await getReviewData();
                } else {
                  message.warning("值不能为空");
                }
                useInputStuts({
                  ...inputStuts,
                  [value]: false,
                });
              }}
            />
          );
        }
        return (
          <p
            onClick={() => {
              useInputStuts({
                ...inputStuts,
                [value]: true,
              });
              setTimeout(() => {
                input.current?.focus();
              }, 0);
            }}
          >
            {value}
          </p>
        );
      },
    },
    {
      title: "操作",
      render(item: slectType) {
        return (
          <Button
            children="删除"
            danger
            onClick={() => {
              confirm({
                title: "确定删除吗",
                cancelText: "取消",
                okText: "确定",
                onOk: async () => {
                  await reqDelNewsCategory(item.id);
                  await getReviewData();
                  message.success("已删除");
                },
              });
            }}
          />
        );
      },
    },
  ];

  useEffect(() => {
    globalStore.data.titel = "审核列表";
    getReviewData();
  }, []);
  return <Table dataSource={data} columns={columns} rowKey="id" />;
}
